package com.zcah.repository;


import com.zcah.model.Article;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ArticleService {

    @Autowired
    private Client client;

    public void saveArticle(Article article) {
        try {
            // 使用XContentBuilder创建一个doc source
            XContentBuilder builder =
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("title", article.getTitle())
                            .field("url", article.getUrl())
                            .field("publishDate", article.getPublishDate())
                            .field("crawlDate", article.getCrawlDate())
                            .field("wechatName", article.getWechatName())
                            .field("nickName", article.getNickName())
                            .field("biz", article.getBiz())
                            .field("roundHeadImg", article.getRoundHeadImg())
                            .field("function", article.getFunction())
                            .field("msgCdnUrl", article.getMsgCdnUrl())
                            .field("content", article.getContent())
                            .field("html", article.getHtml())
                            .field("desc", article.getDesc())
                            .endObject();

            IndexResponse indexResponse = this.client
                    .prepareIndex()
                    .setIndex("wechat76")
                    .setType("article")
                    .setSource(builder.string())
                    .get();
        } catch (ElasticsearchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

